package dao

import models.Tables._
import org.joda.time.DateTime
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile
import tool.Pojo.QData

import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class HcircCpmDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends
  HasDatabaseConfigProvider[JdbcProfile] {


  import utils.MyPostgresProfile.api._

  type MyRow = HcircCpmRow
  val table = HcircCpm

  def selectAll(circId: String) = db.run(table
    .filter(_.circId.toLowerCase === circId.toLowerCase).result)


  def insert(row: MyRow) = {
    db.run(table += row)
  }

  def insertAll(rows: Seq[MyRow]) = db.run(table ++=
    rows)

  def deleteAll(): Future[Unit] = db.run(table.delete).map(_ => ())

  def getTrueColumnName(x: String) = {
    val r = "([A-Z])".r
    r.replaceAllIn(x, (matcher) =>
      s"_${matcher.group(1).toLowerCase}"
    )
  }

  def selectUniqueValues(keys: List[String]) = {
    val action = DBIO.sequence {
      val rs = keys.map { key =>
        val trueColumnName = getTrueColumnName(key)
        table.map { t =>
          t.getStrColumn(trueColumnName)
        }.distinct.result
      }
      rs
    }
    db.run(action)
  }

}
